import React, { useEffect, useState } from 'react';
import { Row, Col, Input, Spin, Tag, Table } from 'antd';
import { QuestionCircleOutlined } from '@ant-design/icons';
import styles from '../Submit.module.css';

interface TestResultProps {
  testInput: string;
  testResult: any;
  submitting: boolean;
  resultActiveTab: string;
  onTestInputChange: (value: string) => void;
  onTest: () => void;
  expectedOutput?: string;
  onExpectedOutputChange?: (value: string) => void;
}

const TestResult: React.FC<TestResultProps> = ({
  testInput,
  testResult,
  submitting,
  resultActiveTab,
  onTestInputChange,
  onTest,
  expectedOutput = '',
  onExpectedOutputChange = () => {}
}) => {
  // 管理输入框焦点状态
  const [testInputFocused, setTestInputFocused] = useState(false);
  const [expectedOutputFocused, setExpectedOutputFocused] = useState(false);
  // 确保testCases中的预期输出更新为用户输入的值
  useEffect(() => {
    if (testResult && testResult.testCases && testResult.testCases.length > 0) {
      // 创建一个更新后的testCases副本
      const updatedTestCases = testResult.testCases.map((testCase: any) => ({
        ...testCase,
        expected: expectedOutput || testCase.expected || ''
      }));
      
      // 更新testResult中的testCases
      testResult.testCases = updatedTestCases;
    }
  }, [testResult, expectedOutput]);

  // 渲染测试输出结果
  const renderTestOutput = () => {
    if (submitting && resultActiveTab === 'testResult') {
      return (
        <div className={styles.loadingContainer}>
          <Spin>
            <div className={styles.loadingPlaceholder} style={{ minHeight: '100px' }} />
          </Spin>
        </div>
      );
    }
    
    if (testResult) {
      // 准备表格数据，确保正确使用用户输入的预期输出
      const tableData = testResult.testCases ? testResult.testCases.map((testCase: any, index: number) => {
        // 如果是第一个测试用例，使用用户输入的预期输出
        const expected = index === 0 ? expectedOutput : testCase.expected || '';
        
        // 只有在有预期输出时才进行匹配判断
        const isPass = expected ? testCase.output === expected : true;
        
        return {
          ...testCase,
          key: index,
          expected: expected,
          result: isPass ? 'Pass' : 'Fail'
        };
      }) : [];

      return (
        <div className={styles.testResultOutput}>
          <div className={styles.resultInfo}>
            <Tag color={testResult.status === 'Accepted' ? 'success' : 'error'}>
              {testResult.status === 'Accepted' ? '执行成功' : '执行失败'}
            </Tag>
            <span>运行时间: {testResult.runtime}</span>
            <span>内存消耗: {testResult.memory}</span>
          </div>
          
          {testResult.errorInfo && (
            <div className={styles.errorInfo}>
              <pre>{testResult.errorInfo}</pre>
            </div>
          )}
          
          <div className={styles.testCaseResult}>
            <Table
              dataSource={tableData}
              columns={[
                { 
                  title: '输出', 
                  dataIndex: 'output', 
                  key: 'output',
                  render: (text: string) => (
                    <pre className={styles.outputText}>
                      {text || '无输出'}
                    </pre>
                  )
                },
                ...(expectedOutput ? [
                  {
                    title: '预期输出', 
                    dataIndex: 'expected', 
                    key: 'expected',
                    render: (text: string) => (
                      <pre className={styles.outputText}>
                        {text || '未提供预期输出'}
                      </pre>
                    )
                  },
                  {
                    title: '匹配', 
                    dataIndex: 'result', 
                    key: 'result',
                    width: 80,
                    render: (text:any) => (
                      <Tag color={text === 'Pass' ? 'success' : 'error'}>
                        {text === 'Pass' ? '匹配' : '不匹配'}
                      </Tag>
                    )
                  }
                ] : []),
              ]}
              pagination={false}
              size="small"
              className={styles.testCaseTable}
              scroll={{ x: 'max-content' }}
            />
          </div>
        </div>
      );
    }
    
    return (
      <div className={styles.emptyResult}>
        <QuestionCircleOutlined className={styles.emptyIcon} />
        <p>请输入测试数据并点击顶部的"运行测试"按钮</p>
      </div>
    );
  };

  return (
    <div className={styles.resultContent}>
      <Row gutter={[16, 16]}>
        <Col span={24}>
          <div className={styles.testInputsContainer}>
            <Row gutter={16}>
              <Col span={12}>
                <div className={styles.inputGroup}>
                  <div className={styles.inputLabel}>输入测试数据:</div>
                  <Input.TextArea
                    placeholder="请输入测试数据..."
                    value={testInput}
                    onChange={e => onTestInputChange(e.target.value)}
                    rows={testInputFocused ? 4 : 2}
                    className={styles.testInput}
                    onFocus={() => setTestInputFocused(true)}
                    onBlur={() => setTestInputFocused(false)}
                  />
                </div>
              </Col>
              <Col span={12}>
                <div className={styles.inputGroup}>
                  <div className={styles.inputLabel}>预期输出结果（可选）:</div>
                  <Input.TextArea
                    placeholder="请输入预期输出结果（可选）..."
                    value={expectedOutput}
                    onChange={e => onExpectedOutputChange(e.target.value)}
                    rows={expectedOutputFocused ? 4 : 2}
                    className={styles.testInput}
                    onFocus={() => setExpectedOutputFocused(true)}
                    onBlur={() => setExpectedOutputFocused(false)}
                  />
                </div>
              </Col>
            </Row>
          </div>
        </Col>
        <Col span={24}>
          {renderTestOutput()}
        </Col>
      </Row>
    </div>
  );
};

export default TestResult; 